import io

from finder import Finder
from docx import Document
import tools
import os
import pytesseract
from PIL import Image
from pathlib import Path
import zipfile


class WordFinder(Finder):
    @staticmethod
    def file_suffixes():
        return ["docx"]

    def search_file(self, file_path, search_content):
        doc = Document(file_path)
        paragraph_index = 1

        # 处理word中的文字
        for para in doc.paragraphs:
            text = para.text
            with tools.lock:
                tools.global_store[f'{file_path}_paragraph_{paragraph_index}'] = text
            pass

            if search_content.lower() in Finder.process_text_if_need(text.lower()):
                print(f'Found {search_content} in {file_path} on paragraph {paragraph_index}')
            paragraph_index = paragraph_index + 1

        # 使用zipfile打开docx文件，这里只能将图片拷贝到某个目录中才可以拿到绝对路径
        with zipfile.ZipFile(file_path, 'r') as zip_ref:
            # 遍历zip文件中的所有文件和文件夹
            for zip_info in zip_ref.infolist():
                # 检查文件是否以'word/media/'开头，这通常是图片存储的位置
                image_file_path = zip_info.filename
                if image_file_path.startswith('word/media/'):
                    # 提取文件扩展名
                    _, ext = os.path.splitext(image_file_path)
                    # 检查是否是图片文件
                    if ext.lower() in ['.png', '.jpg', '.jpeg']:
                        try:
                            with zip_ref.open(zip_info.filename) as file:
                                try:
                                    word_image = Image.open(io.BytesIO(file.read()))
                                    image_text = pytesseract.image_to_string(word_image, "chi_sim")
                                    image_result_path = Path(f'{image_file_path}')
                                except Exception as e:
                                    print("Error:Word中图片处理出现异常")
                                with tools.lock:
                                    tools.global_store[f'{file_path}_image_{image_result_path.name}'] = image_text
                                pass

                                if search_content.lower() in Finder.process_text_if_need(image_text.lower()):
                                    print(f'Found {search_content} in {file_path} on image {image_result_path.name}')
                        except KeyError:
                            print(f"File {zip_info.filename} not found in the zip file.")

        del doc
